package com.foo.common.base.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.validator.routines.EmailValidator;
import org.apache.commons.validator.routines.InetAddressValidator;
import org.apache.commons.validator.routines.IntegerValidator;

public class ValidateHelper {

	/**
	 * 手机号验证
	 * 
	 * @param str
	 * @return 验证通过返回true
	 */
	public static boolean isMobileValid(String str) {
		if (str == null) {
			return false;
		}
		Pattern p = null;
		Matcher m = null;
		boolean b = false;
		p = Pattern.compile("^[1][3,4,5,8][0-9]{9}$"); // 验证手机号
		m = p.matcher(str);
		b = m.matches();
		return b;
	}

	public static boolean isEmailValid(String email) {
		if (email == null) {
			return false;
		}
		return EmailValidator.getInstance().isValid(email);
	}

	public static boolean IsIntegerValid(String value) {
		if (value == null) {
			return false;
		}
		return IntegerValidator.getInstance().isValid(value);
	}

	/**
	 * 电话号码验证
	 * 
	 * @param str
	 * @return 验证通过返回true
	 */
	public static boolean isPhoneValid(String str) {
		if (str == null) {
			return false;
		}
		Pattern p1 = null, p2 = null;
		Matcher m = null;
		boolean b = false;
		p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$"); // 验证带区号的
		p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$"); // 验证没有区号的
		if (str.length() > 9) {
			m = p1.matcher(str);
			b = m.matches();
		} else {
			m = p2.matcher(str);
			b = m.matches();
		}
		return b;
	}

	public static boolean isInetAddressValid(String data) {
		if (data == null) {
			return false;
		}
		return InetAddressValidator.getInstance().isValid(data);
	}

	private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory
			.getLogger(ValidateHelper.class);

	public static void main(String[] args) {
		logger.info("Result is:{}", isMobileValid("186281499523"));
		logger.info("Result is:{}", isPhoneValid("028-545435"));
		logger.info("Result is:{}", isEmailValid("nevermissing@vip.qq.com"));
		logger.info("Result is:{}", IsIntegerValid("dasd"));
		logger.info("Result is:{}", isInetAddressValid("120.123.123.12"));
	}
}
